<?php
namespace app\api\controller\deerhome\user;

use app\api\controller\deerhome\user\Base;
use app\admin\model\deerhome\CardOrder as CardOrderModel;
use app\admin\model\deerhome\OrderPayLog as OrderPayLogModel;
use EasyWeChat\Kernel\Messages\Raw;
use think\Db;
use think\Log;
/**
 * 微信支付回调::次卡购买
*/
class NotifyCard extends Base
{
    public function index()
    {
        $_order_payed=false;
        $order_sn=$this->request->param("sn",'');
        $notifyCon=\WeChat\Contracts\Tools::getRawInput();
        if($notifyCon){
            Log::write('【微信支付-次卡购买-回调】：'.json_encode($notifyCon));
        }
      
        if($order_sn=="" && $notifyCon=="" ){
            Log::error('【微信支付-次卡购买-回调】订单号为空，且没有post数据');
            return;
        }
        $order=[];
        Db::startTrans();
        try {
            $config=$this->getWeixinConfig();
            $payment = \WePayV3\Order::instance($config);
            if($order_sn==""){
                $data = $payment->notify();
                $result=\json_decode($data['result'],true);
                $order_sn=$result['out_trade_no'];
            }
           
            $order=OrderPayLogModel::where("type",3)->where("order_sn",$order_sn)->find();
            if(!$order){
                throw new \Exception("次卡购买交易不存在");
            }
            if($order['status']!=1){
                throw new \Exception("该次卡购买交易状态已不可支付");
            }
   
            $need_pay=$order['price'];
            $need_pay=$need_pay*100;
            $orderQuery=$payment->query($order_sn);
            if(!isset($orderQuery['trade_state'])){
                throw new \Exception("次卡购买订单查询失败:".$orderQuery['message']);
            }
            if($orderQuery['trade_state']=="SUCCESS" ){
                if($orderQuery['amount']['payer_total']!=$need_pay){
                    throw new \Exception("次卡购买订单支付金额不正确，应支付￥{$need_pay}分，实际支付￥{$orderQuery['amount']['payer_total']}分");
                }
            }else{
                throw new \Exception("次卡购买订单交易状态[{$orderQuery['trade_state']}]");
            }

            $pay_time=date("Y-m-d H:i:s",strtotime($orderQuery['success_time']));
            
            (new CardOrderModel)->payed($order_sn,'微信支付',$pay_time);

            Db::commit();
            echo '{"code","SUCCESS","msg":"OK"}}';
        } catch (\Exception $e) {
            echo '{"code","FAIL","msg":"'.$e->getLine()."|".$e->getMessage().'"}}';
            Log::error('【微信支付-储值卡-回调】充值'.$order_sn.'错误信息:'.$e->getLine()."|".$e->getMessage() );
        }
        return;
    }
}
?>